package top.lyjwn.todo.conf;

import io.swagger.annotations.ApiOperation;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.event.AppLoadEndEvent;
import org.noear.solon.core.event.EventListener;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.mvc.ActionDefault;
import org.noear.solon.core.route.Router;
import org.noear.solon.core.route.Routing;
import org.noear.solon.core.wrap.MethodWrap;
import top.lyjwn.todo.permission.PermissionInfo;
import top.lyjwn.todo.permission.PermissionPool;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
public class AppLoadEndEventListener implements EventListener<AppLoadEndEvent> {

    @Inject
    private PermissionPool permissionPool;

    @Inject("${todo.token.excludePaths}")
    private String excludePaths;

    @Override
    public void onEvent(AppLoadEndEvent event) throws Throwable {
        //event.app(); //获取应用对象
        //event.app().converterManager();
        registerPermissionInfo(event.app().router());
    }

    private void registerPermissionInfo(Router router) {
        for (Routing<Handler> handlerRouting : router.getAll()) {
            String url = handlerRouting.path();
            if (excludePaths.contains(url)) continue;
            String url_replace = url.replace("\\", "/");
            String[] url_replace_split = url_replace.split("/");
            List<String> urlPaths = new ArrayList<>();
            for (String s : url_replace_split) {
                if (s != null && !"".equals(s)) {
                    urlPaths.add(s);
                }
            }
            PermissionInfo permissionInfo = new PermissionInfo();
            permissionInfo.setUrl(url);
            if (handlerRouting.target() instanceof ActionDefault) {
                MethodWrap methodWrap = ((ActionDefault) handlerRouting.target()).method();
                Method method = methodWrap.getMethod();
                permissionInfo.setMethodName(method.getName());
                ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
                if (apiOperation != null) {
                    String description = apiOperation.value();
                    permissionInfo.setMark(description);
                }
            }

            String[] array = urlPaths.toArray(urlPaths.toArray(new String[urlPaths.size()]));
            String join = String.join(":", array);
            permissionInfo.setCode(join);
            permissionPool.getCodePool().put(permissionInfo.getCode(), permissionInfo);
            permissionPool.getUrlPool().put(permissionInfo.getUrl(), permissionInfo);
        }
    }
}
